const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g;

function genProps(attrs) {
  let str = "";
  for (const key in attrs) {
    let attr = attrs[key]; // name, value
    if (attr.name === "style") {
      let obj = {};
      attr.value.split(";").forEach((item) => {
        let [key, value] = item.split(":");
        obj[key] = value;
      });

      attr.value = obj;
    }
    str += `${attr.name}:${JSON.stringify(attr.value)},`;
  }
  return `{${str.slice(0, -1)}`;
}

function genChildren(el) {
  const children = el.children;
  if (children) {
    return children.map((child) => gen(child)).join(",");
  }
}

function gen(node) {
  // 区分元素 / 文本
  //  生成代码
  console.log(node);
  if (node.type === 1) {
    return generate(node);
  } else {
    //  文本逻辑  _c来处理
    // {{}} 普通文本 混合的  bbb {{}} aa
    let text = node.text;
    if (defaultTagRE.test(text)) {
      //  包含{{}}
      let tokens = [];
      let match;
      let index = 0;
      let lastIndex = defaultTagRE.lastIndex;
      console.log((match = defaultTagRE.exec(text)));
      while ((match = defaultTagRE.exec(text))) {
        // tokens.push();
        index = match.index;
        if (index > lastIndex) {
          tokens.push(JSON.stringify(text.slice(lastIndex)));
          // debugger;
        } else {
        }
      }
    } else {
      return `-v(${JSON.stringify(text)})`;
    }
  }
}

export function generate(el) {
  let children = genChildren(el);
  let code = `_c('${el.tag}', ${
    el.attrs.length ? genProps(el.attrs) : undefined
  } ${children ? "," + children : ""})`;
  //ast==>转化成render代码 ，render生成的就是虚拟dom

  // html ==> js代码

  return code;
}
